﻿using Microsoft.AspNetCore.Mvc;
using SaiLing.Common;
using SaiLing.Domain.Specification;
using SaiLing.SingleSignOn.Application.Core.Controllers;
using SaiLing.SingleSignOn.Application.Core.DataTransferObject.System;
using SaiLing.SingleSignOn.Application.Core.Params;
using SaiLing.SingleSignOn.Application.Service;
using SaiLing.SingleSignOn.Application.Service.Interfaces.System;
using SaiLing.SingleSignOn.Domain.Entities.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SaiLing.SingleSignOn.WebApi.Controllers
{
    public class OrganizationController : BaseController
    {
        private IOrganizationService OrganizationService { get; set; }

        private IOrganizationMenuAuthorityService OrganizationMenuAuthorityService { get; set; }

        public OrganizationController(IOrganizationService organizationService, IOrganizationMenuAuthorityService organizationMenuAuthorityService)
        {
            this.OrganizationService = organizationService;
            OrganizationMenuAuthorityService = organizationMenuAuthorityService;
        }

        [HttpGet]
        public async Task<ApiJsonResultData> GetByKey(Guid id)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                x.Data = await OrganizationService.GetByKey(id);
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> List(string name)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var list = await OrganizationService.List(name);
                x.Data = list;
            });
        }

        /// <summary>
        /// 获取功能模块列表--树形
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public  ApiJsonResultData TreeList()
        {
            return new ApiJsonResultData().RunWithTry(x =>
            {
                var modules = OrganizationService.GetMany(new DirectSpecification<Organization>(m => m.LogicRemove == false)).OrderBy(m => m.Sort).Select(m => new TreeNode()
                { Text = m.FullName, Id = m.Id, ParentId = m.ParentId }).ToList().ToTree(new List<TreeNode>(), Guid.Empty, 1);
                var menus = new[] { new TreeNode() { Text = "顶级模块", Id = Guid.Empty } };
                x.Data = menus.Concat(modules);
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> PageList(int pageIndex, int pageSize, string name)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var list = await OrganizationService.PageList(pageIndex, pageSize, name);
                x.Data = list;
            });
        }

        public async Task<ApiJsonResultData> Create([FromForm]Organization model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var result = await OrganizationService.Create(model);
                x.AddMessage("创建成功");
                x.Data = result;
                x.RedirectUrl = @return;
            });
        }

        public async Task<ApiJsonResultData> Edit([FromForm]Organization model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var result = await OrganizationService.Edit(model);
                x.AddMessage("修改成功");
                x.Data = result;
                x.RedirectUrl = @return;
            });
        }

        [HttpPost]
        public async Task<ApiJsonResultData> Delete([FromBody]List<RemoveParam> model)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                if (model != null && model.Any())
                {
                    var list = new List<Organization>();
                    model.ToList().ForEach(f =>
                    {
                        list.Add(new Organization { Id = f.Id });
                    });
                    var rulst = await OrganizationService.Delete(list.ToArray());
                    x.ReloadPage = true;
                    x.Data = rulst;
                    x.AddMessage("删除成功");
                }
                else
                    x.AddErrorMessage("至少选择一条数据");
            });
        }

        #region 权限操作
        /// <summary>
        /// 获取组织机构权限
        /// </summary>
        /// <param name="parentOrganizationId"></param>
        /// <param name="organizationId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiJsonResultData> GetOrganizationAuthority(Guid? parentOrganizationId = default(Guid?), Guid? organizationId = default(Guid?))
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                x.Data = OrganizationService.GetOrganizationAuthorityObject(parentOrganizationId, organizationId);
            });
        }

        [HttpGet]
        public async Task<ApiJsonResultData> MenuAuthorityList(Guid? organizationId, Guid? moduleId, Guid? moduleActionId, Guid? appid)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var list = await OrganizationMenuAuthorityService.List(organizationId, moduleId, moduleActionId, appid);
                x.Data = list;
            });
        }

        /// <summary>
        /// 为部门分配权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="return"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiJsonResultData> Save([FromForm]Organization model, string @return)
        {
            return await new ApiJsonResultData().RunWithTryAsync(async x =>
            {
                var result = await OrganizationService.Create(model);
                x.AddMessage("创建成功");
                x.Data = result;
                x.RedirectUrl = @return;
            });
        }

        #endregion

    }
}
